#include "../Include/Bitmap.h"

Bitmap::Bitmap( HINSTANCE hAppInst, const CHAR *pImageFileName, const PositionType posType /*= POS_UPPER_LEFT*/, const BlendOptions bOp /*= BLEND_SRC_COPY*/ )
	: m_posType( posType ), m_blendOp( bOp )
{
	PSX_ThrowAssert( pImageFileName, "Specified filename can not be null." );

	m_hBitmap = (HBITMAP)LoadImage( hAppInst, pImageFileName, IMAGE_BITMAP, 0, 0, LR_DEFAULTCOLOR | LR_LOADFROMFILE );
	try { PSX_ThrowAssert( m_hBitmap, "Failed to create image." ); }
	catch ( Exception e )
	{
		MessageBox( NULL, e.GetMessage(), "Error", MB_ICONERROR );
		return;
	}

	// Get the image structure for the loaded bitmap
	GetObject( m_hBitmap, sizeof( BITMAP ), &m_bmInfo );
}

Bitmap::~Bitmap( void )
{
	DeleteObject( m_hBitmap );
}

void Bitmap::Render( HDC hBBDC, HDC hSprDC, INT x, INT y )
{
	HGDIOBJ oldObj = SelectObject( hSprDC, m_hBitmap );

	TranslatePosition( x, y );

	BitBlt( hBBDC, x, y, GetWidth(), GetHeight(), hSprDC, 0, 0, m_blendOp );

	// Restore old object then we're done!
	SelectObject( hSprDC, oldObj );
}

void Bitmap::Render( HDC hBBDC, HDC hSprDC, INT x, INT y, INT w, INT h, INT srcX, INT srcY )
{
	HGDIOBJ oldObj = SelectObject( hSprDC, m_hBitmap );

	TranslatePosition( x, y );

	BitBlt( hBBDC, x, y, w, h, hSprDC, srcX, srcY, m_blendOp );

	// Restore old object then we're done!
	SelectObject( hSprDC, oldObj );
}


void Bitmap::TranslatePosition( INT &x, INT &y )
{
	// We don't have to do anything if PosType is UPPER_LEFT
	if ( m_posType == POS_CENTER )
	{
		// Calculate center pos.
		x -= GetWidth()/2;
		y -= GetHeight()/2;
	}
}

Pulse::BOOL Bitmap::TestPoint( INT x, INT y )
{
	// General rect collision test first
	return x >= 0 && x < m_bmInfo.bmWidth && y >= 0 && y < m_bmInfo.bmHeight;
}